import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import documentRouters from './router-document.js'
import editorRouters from './router-editor.js'

import { logout } from '@/utils'
import { getParam } from '../utils/parameter'
import http from '@/utils/request'

const originalPush = Router.prototype.push
Router.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(Router)

// 全局路由
const globalRoutes = [
  {
    path: '/login',
    name: 'login',
    component: resolve => require(['@/views/common/login.vue'], resolve),
    meta: { title: '登录' }
  },
  {
    path: '/404',
    name: '404',
    component: resolve => require(['@/views/common/error/404.vue'], resolve),
    meta: { title: '404未找到' }
  },
  {
    path: '/403',
    name: '403',
    component: resolve => require(['@/views/common/error/403.vue'], resolve),
    meta: { title: '403无权限' }
  },
  {
    path: '*',
    redirect: { name: '404' }
  }
]

// 主入口路由
const mainRoutes = {
  path: '/',
  name: 'home',
  redirect: { name: 'dashboard' },
  component: resolve => require(['@/views/common/home.vue'], resolve),
  children: [
    {
      path: '/dashboard',
      name: 'dashboard',
      component: resolve => require(['@/views/common/Dashboard.vue'], resolve),
      meta: { title: '首页' }
    },
    // 如果不需要 组件文档 请注销
    ...documentRouters,
    ...editorRouters
  ]
}

const router = new Router({
  //mode: 'history',
  isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
  routes: globalRoutes.concat(mainRoutes)
})

router.beforeEach((to, from, next) => {
  let token = store.state.user.accessToken
  if (token) {
    // 登录状态下 访问login页面跳转到home主页
    const path = to.path
    if (path === '/login') {
      next({ name: 'home' })
    } else {
      if (router.options.isAddDynamicMenuRoutes || isGlobalPath(path)) {
        next()
      } else {
        // 根据token获取不同用户的权限路由
        const userMockJS = getParam('userMockJS')
        // 若使用mockjs模拟数据,请带上token,否则正常request请求的请求头会带上token
        const url = userMockJS ? '/base/authMenu/' + token : '/base/authMenu'
        http.get(http.adornUrl(url)).then(({data}) => {
          const result = data
          if (result.code === 200) {
            const data = result.data
            // 处理数据并添加动态路由
            dealDynamicMenu(data['menus'])
            router.options.isAddDynamicMenuRoutes = true
            // 往store保存菜单列表 和 权限列表
            store.dispatch('menu/init_menu_data', data)
            next()
          } else {
            // 清除store的 菜单列表 和 权限列表
            store.dispatch('menu/clean_menu_data')
            next()
          }
        }).catch((e) => {
          console.log(`%c${e} 请求菜单列表和权限失败，跳转至登录页！！`)
          logout()
          router.push({ name: 'login' })
        })
      }
    }
  } else {
    // 若无Token,访问任何页面都会跳转到登录页
    if (to.path === '/login') {
      next()
    } else {
      logout()
      next({ name: 'login' })
    }
  }
})

/**
 * 过滤globalRoutes的路径，查询全局路由列表是否存在当前path
 * @param path  当前浏览器path
 * @returns {boolean}
 */
function isGlobalPath (path) {
  return globalRoutes.some(item => {
    return path === item.path
  })
}

/**
 * 处理数据 将 菜单数组列表 转成 动态(菜单)路由列表
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function dealDynamicMenu (menuList = [], routeList = []) {
  let temp = []
  menuList.forEach(item => {
    if (item.url === '' || item.children.length > 0) {
      temp = temp.concat(item.children)
    } else {
      let route = {
        name: item.name,
        path: `/${item.url}`,
        component: null,
        meta: {title: item.title}
      }
      try {
        route.component = () => import(`@/views/modules/${item.url}`)
      } catch (e) {
        console.log(`not find filePath[/views/modules/${item.url}]`)
      }
      routeList.push(route)
    }
  })
  if (temp.length > 0) {
    dealDynamicMenu(temp, routeList)
  } else {
    AddDynamicRoutes(routeList)
  }
}

/**
 * 往router添加动态(菜单)路由
 * @param routeList 动态路由列表
 * @constructor
 */
function AddDynamicRoutes (routeList) {
  let dynamicRoutes = {
    path: '/',
    name: 'home-dynamic',
    redirect: { name: 'dashboard' },
    component: resolve => require(['@/views/common/home.vue'], resolve),
    children: routeList
  }
  // 往router添加动态(菜单)路由
  router.addRoutes([
    dynamicRoutes
  ])
}

export default router
